(function ($, _, amplify, window, document) {
    'use strict';

    var rootElem,
        formElem,
        pageTableBody,
        buildButton,
        headerMenuId,
        footerMenuId,
        serviceType;

    $(document).ready(function () {
        rootElem        = $('#natext .page-builder');
        formElem        = $('.main-form', rootElem);
        pageTableBody   = $('.page-builder-tbody', formElem);
        buildButton     = $('.build-button', formElem);
        headerMenuId    = $('[name="header_menu_id"]', formElem).val();
        footerMenuId    = $('[name="footer_menu_id"]', formElem).val();
        serviceType     = $('[name="service_type"]', formElem).val();


        // Event Listeners
        // ------------------------------

        formElem.submit(formElem_onSubmit);
    })


    // Event Handlers
    // ------------------------------

    function formElem_onSubmit(evt) {
        // prevent the form from submitting to its action URL
        // we'll do it the AJAX way
        evt.preventDefault();

        var pages       = getValidPages(),
            pagesLen    = _.size(pages),
            pageCount   = 0;

        var createPage = function () {
            var page = pages[pageCount];

            // tell the user that we are currently creating the page
            amplify.publish('creatingPage', {sideNote: page.sideNote});

            $.ajax({
                type    : 'POST',
                url     : NatExt.wp.ajax_url,
                data    : {
                    'action'        : 'NatExtAjax_BuildPages',
                    'post_name'     : page.post_name,
                    'post_title'    : page.post_title,
                    'menu_title'    : page.menu_title,
                    'menu_order'    : page.menu_order,
                    'post_content'  : page.post_content,
                    'last_page'     : (pageCount === pagesLen - 1) ? 'true' : 'false',
                    'header_menu_id': headerMenuId,
                    'footer_menu_id': footerMenuId,
                    'service_type'  : serviceType
                },
                success : function () {
                    amplify.publish('pageCreated', {
                        row : page.row,
                        sideNote: page.sideNote
                    });
                },
                complete : function () {
                    pageCount += 1;

                    if (pageCount < pagesLen) {
                        createPage();
                    } else {
                        amplify.publish('allPagesCreated');
                    }
                }
            });
        };

        if (pages.length) {
            // we have valid pages, let's create those

            // hide the build button first
            buildButton.fadeOut(200);

            createPage();
        }
    }


    // Subscriptions
    // ------------------------------

    amplify.subscribe('creatingPage', __creatingPage);
    amplify.subscribe('pageCreated', __pageCreated);
    amplify.subscribe('allPagesCreated', __allPagesCreated);

    function __creatingPage(data) {
        if (! data.sideNote.hasClass('creating-page')) {
            data.sideNote.html('creating page...').addClass('creating-page');
        }
    }

    function __pageCreated(data) {
        if (! data.sideNote.hasClass('page-created')) {
            data.sideNote.html('page created').addClass('page-created');
        }

        // disable the fields on this row
        $('input, textarea', data.row).attr('disabled', 'disabled');

        // uncheck this row
        $('input[type=checkbox]', data.row).removeAttr('checked');
    }

    function __allPagesCreated() {
        setTimeout(function () {
            window.location = NatExt.wp.admin_url + '?page=natext';
        }, 3000);
    }


    // Utils
    // ------------------------------

    function getValidPages() {
        var checkedRows,
            result = [];

        // get all rows of checked pages
        checkedRows = $('input[type=checkbox]:checked', pageTableBody).closest('tr');

        checkedRows.each(function () {
            var row = $(this).get()[0];

            if (hasValidPageData(row)) {
                result.push(getPageData(row));
            }
        });

        return result;
    }

    function getPageData(row) {
        return {
            'row'           : $(row),
            'post_name'     : $(row.cells[1]).text(),
            'post_title'    : $('input', $(row.cells[2])).val(),
            'menu_title'    : $('input', $(row.cells[3])).val(),
            'menu_order'    : $('input', $(row.cells[4])).val(),
            'post_content'  : $('textarea', $(row.cells[5])).val(),
            'sideNote'      : $(row.cells[6])
        };
    }

    function hasValidPageData(row) {
        var pageData = getPageData(row);

        return (($.trim(pageData.post_title) !== '') && ($.trim(pageData.menu_title) !== ''));
    }
}(jQuery, _, amplify, window, document));